package com.young.sso.Service.impl;


import com.young.sso.Service.SmsService;
import com.young.sso.common.ExceptionCode;
import com.young.sso.exception.BusinessException;
import com.young.sso.util.SendSms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * Transactional,业务中使用redis，应该用Transactional管理redis的连接：操作完毕会自动执行关闭连接
 * 阿里规约中规定Transactional必须配置rollbackFor
 *
 * @author young
 * @date 2021/11/29 15:33
 */
@Service
@Transactional(rollbackFor = Throwable.class)
public class SmsServiceImpl implements SmsService {


    /**
     * 把短信缓存到redis中，30分钟有效时间
     * 切记，要配置key，value的序列化方法RedisSerializable
     */
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * redis存储的key设为常量
     */
    public static final String LOGIN_SMS = "login_sms:";

    @Override
    public String sendLoginSms(String phone) throws BusinessException {
        String msgCode;
        try {
            msgCode = SendSms.getMsgCode();

            System.out.println("========验证码========" + msgCode);


            ValueOperations<String, Object> stringOps = redisTemplate.opsForValue();
            stringOps.set(LOGIN_SMS + phone, msgCode, 5, TimeUnit.MINUTES);
        } catch (Exception e) {
            throw new BusinessException(ExceptionCode.RESPONSE_FALSE);
        }

        return msgCode;
    }
}
